﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.Base.SystemModule
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：研发部
    /// 日 期：2017.03.08
    /// 描 述：数据字典管理服务类
    /// </summary>
    public class DataItemService
    {
        #region 仓储
        Repository<DataItemEntity> _dataItemRepository => new Repository<DataItemEntity>();
        Repository<DataItemDetailEntity> _dataItemDetailRepository => new Repository<DataItemDetailEntity>();
        #endregion
        #region 属性 构造函数
        private string fieldSql;
        private string detailFieldSql;
        public DataItemService()
        {
            fieldSql = @" 
                    t.F_ItemId,
                    t.F_ParentId,
                    t.F_ItemCode,
                    t.F_ItemName,
                    t.F_IsTree,
                    t.F_IsNav,
                    t.F_SortCode,
                    t.F_DeleteMark,
                    t.F_EnabledMark,
                    t.F_Description,
                    t.F_CreateDate,
                    t.F_CreateUserId,
                    t.F_CreateUserName,
                    t.F_ModifyDate,
                    t.F_ModifyUserId,
                    t.F_ModifyUserName
                    ";
            detailFieldSql = @"
                    t.F_ItemDetailId,
                    t.F_ItemId,
                    t.F_ParentId,
                    t.F_ItemCode,
                    t.F_ItemName,
                    t.F_ItemNameEN,
                    t.F_ItemValue,
                    t.F_QuickQuery,
                    t.F_SimpleSpelling,
                    t.F_IsDefault,
                    t.F_SortCode,
                    t.F_DeleteMark,
                    t.F_EnabledMark,
                    t.F_Description,
                    t.F_CreateDate,
                    t.F_CreateUserId,
                    t.F_CreateUserName,
                    t.F_ModifyDate,
                    t.F_ModifyUserId,
                    t.F_ModifyUserName
                    ";
        }
        #endregion

        #region 数据字典分类管理
        /// <summary>
        /// 分类列表
        /// </summary>
        /// <returns></returns>
        public IEnumerable<DataItemEntity> GetClassifyList()
        {
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("SELECT " + fieldSql + " FROM LR_Base_DataItem t WHERE t.F_DeleteMark = 0 Order By t.F_ParentId,t.F_SortCode ");
                //return this.BaseRepository().FindList<DataItemEntity>(strSql.ToString());
                return SqlSugarHelper.Db.SqlQueryable<DataItemEntity>(strSql.ToString()).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 虚拟删除分类数据
        /// </summary>
        /// <param name="keyValue">主键</param>
        public void VirtualDeleteClassify(string keyValue)
        {
            try
            {
                DataItemEntity entity = new DataItemEntity()
                {
                    F_ItemId = keyValue,
                    F_DeleteMark = 1
                };
                _dataItemRepository.Update(entity);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 保存分类数据实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="entity">实体</param>
        public void SaveClassifyEntity(string keyValue, DataItemEntity entity)
        {
            try
            {
                if (string.IsNullOrEmpty(keyValue))
                {
                    entity.Create();
                    _dataItemRepository.Insert(entity);
                }
                else
                {
                    entity.Modify(keyValue);
                    _dataItemRepository.Update(entity);
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

        #region 数据字典明细
        /// <summary>
        /// 获取数据字典明显根据分类编号（公司级）
        /// </summary>
        /// <param name="itemCode">分类编号</param>
        /// <returns></returns>
        public IEnumerable<DataItemDetailEntity> GetDetailList(string itemCode)
        {
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("SELECT " + detailFieldSql + @" FROM LR_Base_DataItemDetail t
                            INNER JOIN LR_Base_DataItem t2 ON t.F_ItemId = t2.F_ItemId
                            WHERE t2.F_ItemCode = @itemCode AND t.F_DeleteMark = 0 AND t.F_EnabledMark = 1 Order By t.F_SortCode
                           ");
                //return this.BaseRepository().FindList<DataItemDetailEntity>(strSql.ToString(), new { itemCode = itemCode });
                return SqlSugarHelper.Db.SqlQueryable<DataItemDetailEntity>(strSql.ToString()).AddParameters(new { itemCode = itemCode }).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取数据字典明显根据分类编号
        /// </summary>
        /// <param name="itemCode">分类编号</param>
        /// <returns></returns>
        public IEnumerable<DataItemDetailEntity> GetDetailListAll(string itemCode)
        {
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("SELECT " + detailFieldSql + @" FROM LR_Base_DataItemDetail t
                            INNER JOIN LR_Base_DataItem t2 ON t.F_ItemId = t2.F_ItemId
                            WHERE t2.F_ItemCode = @itemCode AND t.F_DeleteMark = 0 Order By t.F_SortCode
                           ");
                //return this.BaseRepository().FindList<DataItemDetailEntity>(strSql.ToString(), new { itemCode = itemCode });
                return SqlSugarHelper.Db.SqlQueryable<DataItemDetailEntity>(strSql.ToString()).AddParameters(new { itemCode = itemCode }).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取APP项目过程统计数据字典
        /// </summary>
        /// <param name="F_ItemCode">字典编号</param>
        /// <returns></returns>
        public IEnumerable<DataItemDetailEntity> GetStatisticsList(string F_ItemCode)
        {
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("SELECT t1.* FROM LR_Base_DataItemDetail t1 INNER JOIN LR_Base_DataItem t2 ON t1.F_ItemId=t2.F_ItemId WHERE t2.F_ItemCode=@F_ItemCode AND t1.F_DeleteMark='0' ORDER BY t1.F_ItemValue");
                //return this.BaseRepository().FindList<DataItemDetailEntity>(strSql.ToString(), new { F_ItemCode = F_ItemCode });
                return SqlSugarHelper.Db.SqlQueryable<DataItemDetailEntity>(strSql.ToString()).AddParameters(new { F_ItemCode = F_ItemCode }).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取数据字典明细实体类
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        public DataItemDetailEntity GetDetailEntity(string keyValue)
        {
            try
            {
                //return this.BaseRepository().FindEntity<DataItemDetailEntity>(keyValue);
                return _dataItemDetailRepository.GetById(keyValue);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        public void DeleteDetail(string keyValue)
        {
            try
            {
                DataItemDetailEntity entity = _dataItemDetailRepository.GetById(keyValue);
                _dataItemDetailRepository.Delete(entity);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 虚拟删除明细数据
        /// </summary>
        /// <param name="keyValue">主键</param>
        public void VirtualDeleteDetail(string keyValue)
        {
            try
            {
                DataItemDetailEntity entity = new DataItemDetailEntity()
                {
                    F_ItemDetailId = keyValue,
                    F_DeleteMark = 1
                };
                _dataItemDetailRepository.Update(entity);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 保存明细数据实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="entity">实体</param>
        public void SaveDetailEntity(string keyValue, DataItemDetailEntity entity)
        {
            try
            {
                if (string.IsNullOrEmpty(keyValue))
                {
                    entity.Create();
                    _dataItemDetailRepository.Insert(entity);
                }
                else
                {
                    entity.Modify(keyValue);
                    _dataItemDetailRepository.Update(entity);
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        ///  获取下拉列表类型数据
        /// </summary>
        /// <param name="itemCode">分类编号</param>
        /// <returns></returns>
        public DataTable GetSelectData(string itemCode)
        {
            try
            {
                string strsql = "select t2.F_ItemName as text , t2.F_ItemValue as id from lr_base_dataitem as t1 left join lr_base_dataitemdetail as t2 on t1.F_ItemId = t2.F_ItemId where t1.F_ItemCode =@itemCode";
                return SqlSugarHelper.Db.Ado.GetDataTable(strsql, new { itemCode = itemCode });
            }
            catch (Exception ex)
            {

                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }

        }
        #endregion

        #region 项目过程（获取子分类名称，项目阶段名称，项目过程名称）
        /// <summary>
        /// 获取字典名称
        /// </summary>
        /// <param name="projectProcessType">项目过程分类ItemValue</param>
        /// <param name="projectPhase">项目阶段分类ItemValue</param>
        /// <param name="subProjectProcessType">子分类分类ItemValue</param>
        /// <param name="subItemCode">子分类Code</param>
        /// <returns></returns>
        public DataItemDetailEntity GetCodeName(string projectProcessType, string projectPhase, string subProjectProcessType, string subItemCode)
        {
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append(@"SELECT t1.F_ItemName AS  ProjectProcessTypeName ");

                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!string.IsNullOrEmpty(projectPhase))
                {
                    dp.Add(new SugarParameter("ProjectPhase", projectPhase, DbType.String));
                    strSql.Append(@" ,(SELECT F_ItemName FROM LR_Base_DataItemDetail WHERE  F_ItemValue = @ProjectPhase AND t1.F_DeleteMark = '0'
 AND F_ItemId = (SELECT TOP 1 F_ItemId  FROM LR_Base_DataItem WHERE F_ItemCode = 'BIMCD-ProjectPhase')) AS
    ProjectPhaseName");
                }
                if (!string.IsNullOrEmpty(subProjectProcessType))
                {
                    dp.Add(new SugarParameter("SubProjectProcessType", subProjectProcessType, DbType.String));
                    dp.Add(new SugarParameter("SubItemCode", subItemCode, DbType.String));
                    strSql.Append(@" ,(SELECT F_ItemName FROM LR_Base_DataItemDetail WHERE  F_ItemValue =@SubProjectProcessType AND t1.F_DeleteMark = '0'
     AND F_ItemId = (SELECT TOP 1 F_ItemId  FROM LR_Base_DataItem WHERE F_ItemCode = @SubItemCode)) AS
         SubProjectProcessTypeName");
                }
                dp.Add(new SugarParameter("ProjectProcessType", projectProcessType, DbType.String));
                strSql.Append(@" FROM LR_Base_DataItemDetail t1
INNER JOIN LR_Base_DataItem t2 ON t1.F_ItemId = t2.F_ItemId
WHERE t2.F_ItemCode = 'BIMCD-ProjectProcessType' AND t1.F_DeleteMark = '0'
AND t1.F_ItemValue = @ProjectProcessType");
                return SqlSugarHelper.Db.Ado.SqlQuerySingle<DataItemDetailEntity>(strSql.ToString(), dp);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion
    }
}
